import React, { useEffect, useState } from 'react'
import styles from './my.module.css'
import { useNavigate } from 'react-router-dom'
import { NavBar, Input, Button, Toast } from 'antd-mobile'


//1.声明用户Id 和 服务 Id
const user_id = 1;
const server_id = 7788;

const ws = new WebSocket(
  `ws:124.221.74.149:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`
);

function Index() {
  const nvigate = useNavigate()
  const [message, setmessage] = useState('')
  const [chatlist, setchatlist] = useState([])
  useEffect(() => {
    ws.onopen = () => {
      console.log('连接成功')
      ws.send = (JSON.stringify({ type: 'getChatList' }))
    }
    ws.onmessage = (msg) => {
      const { type, data } = JSON.parse(msg.data)
      console.log(type, data)
      if (type == 'getChatList') {
        setchatlist(data)
      }
      else if (type == 'addMessage') {
        setchatlist((pre) => [...pre, data])
      }

    }
  }, [])
  const [value, setValue] = useState('')
  const [list, setlist] = useState([])
  const fs = () => {
    if (value === '') {
      Toast.show('请输入内容')
      return
    }
    setlist([...list, value])
    setValue('')
  }
  return (
    <div className={styles.lt}>
      <NavBar onBack={() => nvigate('/')}>聊天</NavBar>
      <div className={styles.xx}>
        <div>
          {
            chatlist.map((item, index) => {
              const zy = `chat-list-item-${item.dir == 1 ? 'right' : 'left'} `
              // const tx= item.dir ? item.server_id : item.user_id
              return <div key={index} className={styles[zy]}>
                <div>
                  <img src={tx} className={styles.txx} alt="" />
                  <span className={styles.wz}>{item.name}</span>
                </div>
              </div>
            })
          }
        </div>

      </div>
      <div className={styles.dhz}>

      </div>
      <div className={styles.xz}>
          {
        list.map((item, index) => {
          return <div key={index+1}>
            <dl>
              {/* <dt>{ index}</dt> */}
             <dt>{index + 1}</dt>
              <div className={styles.dd}>
              <img style={{width:'50px', height:'50px'}} src='https://gw.alipayobjects.com/zos/bmw-prod/b874caa9-4458-412a-9ac6-a61486180a62.svg' alt="" />
              
                <dd>{item.name}</dd>
              </div>
              
            </dl>
          </div>
        })
      }
        <div>
         
 </div>
    
        <div className={styles.fs}>
          <Input
          placeholder='请输入内容'
          value={value}
          onChange={val => {
            setValue(val)
          }}
        />
        <Button color='primary' fill='solid' onClick={() => fs()}>
          发送
        </Button>

 </div>
        
      </div>
    </div>
  )
}

export default Index
